package com.hospital.wx.util;

import com.itextpdf.text.log.Logger;
import com.itextpdf.text.log.LoggerFactory;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

/*
 * MinIO存储工具类
 * */
@Component
public class MinioUtil {
    private static final Logger logger = LoggerFactory.getLogger(MinioUtil.class);

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket}")
    private String bucketName;

    /**
     * 上传图片到MinIO
     * @param imageData 图片数据
     * @param fileName 文件名
     * @return 上传后的文件相对路径
     */
    public String uploadImage(byte[] imageData, String fileName) {
        try {
            // 检查bucket是否存在
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }

            // 上传文件
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .stream(new ByteArrayInputStream(imageData), imageData.length, -1)
                            .contentType("image/jpeg")
                            .build()
            );

            // 返回文件路径
            return fileName;
        } catch (Exception e) {
            logger.error("上传文件到MinIO失败", e);
            throw new RuntimeException("上传文件失败: " + e.getMessage());
        }
    }

}
